<template>
  <div class="common-layout">
    <el-container>
      <el-header height="100%">
        <HeaderView />
      </el-header>
      <el-main height="100%" style="background-color: #F5F5F5;">
        <div class="loginbox">
          <h1 style="margin:  0 auto;text-align: center; margin: 30px 0">登录</h1>
          <input type="text" v-model="username" placeholder="用户名" class="text">
          <input type="password" v-model="password" placeholder="密码" class="text password-input">
          <!--验证码组件-->
          <div style="width: 200px;margin: 0 auto">
            <p v-show="!isCode" style="font-size: 12px;color: red;">验证码错误</p>
            <p v-show="isCode" style="color: white;font-size: 12px">你看不见</p>
          </div>
          <div class="dentify">
            <input type="text" class="dentifytext" placeholder="验证码" v-model="usercode">
            <div @click="refreshCode" style="cursor: pointer;">
              <dentify :identifyCode="identifyCode"></dentify>
            </div>
          </div>


          <div class="role-selector">
            <el-radio-group v-model="userRole">
              <el-radio label="guest">用户</el-radio>
              <el-radio label="admin">管理员</el-radio>
            </el-radio-group>
          </div>

          <!-- 修改为两个并列的链接 -->
          <div class="action-links">
            <el-link type="primary" @click="toRegister" :underline="false">注册账号</el-link>
            <el-link type="primary" @click="toForgetPassword" :underline="false">忘记密码？</el-link>
          </div>

          <el-button type="primary" @click="login" color="#B01F24" class="text"
            style="width: 220px; margin: 10px auto 50px;">登录</el-button>
        </div>

      </el-main>
      <el-footer height="100%">
        <FooterView />
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import req from '../utils/request';
import HeaderView from '@/view/HeaderView.vue';
import FooterView from '@/view/FooterView.vue';
import dentify from '@/view/dentify.vue';
import router from '@/router';
import Cookies from 'js-cookie';  // 导入 js-cookie
import { mapActions } from 'vuex'; // 导入 mapActions

export default {
  name: 'LoginView',
  components: {
    HeaderView,
    FooterView,
    dentify
  },
  data() {
    return {
      username: "",
      password: "",
      identifyCode: "",
      identifyCodes: "1234567890abcdefjhijklinopqrsduvwxyz",
      usercode: "",
      isCode: true,
      userRole: 'guest'
    }
  },
  mounted() {
    // 初始化验证码
    this.identifyCode = "";
    //参数：（1）随机串内容。（2）验证码显示位数
    this.makeCode(this.identifyCodes, 4);
  },
  methods: {
    ...mapActions(['updateUserInfo']), // 映射 Vuex 的 action

    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        //通过循环获取字符串内随机几位
        this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    login() {
      if (this.usercode == this.identifyCode) {
        this.isCode = true
        if (this.userRole == 'guest') {
          req.post("/user/login", {
            username: this.username,
            password: this.password
          }).then(res => {
            if (res.code === 200) {
              localStorage.setItem("token", res.data.token)
              const userInfo = res.data.userinfo;
              if (userInfo && userInfo.image) {
                Cookies.set('userAvatar', userInfo.image, { expires: 30 }); // 设置 Cookie，有效期为30天
              }
              this.updateUserInfo(userInfo); // 存储用户信息到 Vuex
              router.push({ name: "home", query: { gender: userInfo.gender } });
            } else {
              alert("登录失败");
            }

          })
        } else if (this.userRole == 'admin') {
          req.post("/admin/login", {
            name: this.username,
            password: this.password
          }).then(res => {
            // console.log(res);
            // localStorage.setItem("token", res.data.token)
            // const userInfo = res.data.userinfo;
            // if (userInfo && userInfo.image) {
            //   Cookies.set('userAvatar', userInfo.image, { expires: 30 }); // 设置 Cookie，有效期为7天
            // }
            // this.updateUserInfo(userInfo); // 存储用户信息到 Vuex
            router.push({ name: "adminIndex" })
          })
        }
      } else {
        this.isCode = false
      }
    },
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    toRegister() {
      router.push({ name: 'register' });
    },
    toForgetPassword() {
      router.push({ name: 'forgetPassword' });
    }
  }
}
</script>

<style scoped>
.loginbox {
  width: 500px;
  margin: 200px auto 100px;
  border: 5px solid #B01F24;
  background-color: white;
  border-radius: 10px;

}

.text {

  margin: 30px auto;
  display: block;
  padding: 0 20px;
}

input {
  width: 200px;
  height: 30px;
  border-radius: 5px;
  background-color: rgb(226, 226, 226);
  border: 0;
  /* padding: 0 20px; */
}

input:focus {
  outline: 2px solid #B01F24
}

.dentify {
  width: 240px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;

}

.dentifytext {
  width: 100px;
  display: block;
  padding: 0 20px;
}

.role-selector {
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 修改单选按钮选中时的颜色 */
:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #B01F24;
  background: #B01F24;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #B01F24;
}

/* 修改鼠标悬停时的颜色 */
:deep(.el-radio__input.is-hover .el-radio__inner) {
  border-color: #B01F24;
}

.password-input {
  margin-bottom: 15px;
}

/* 替换原来的 forget-password 样式 */
.action-links {
  text-align: center;
  display: flex;
  justify-content: center;
  gap: 20px;
  /* 设置两个链接之间的间距 */
}

.action-links .el-link {
  font-size: 12px;
  color: #B01F24;
}

.action-links .el-link:hover {
  color: #d4383f;
}
</style>